import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertest/screens/login_screen.dart';
import 'package:fluttertest/utils/helper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../models/user_model.dart';
import '../../main.dart';
import 'change_password_screen.dart';
import 'edit_profile_screen.dart';

class ProfileScreen extends StatefulWidget {
  const ProfileScreen({super.key});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  UserModel? _userInfo;

  @override
  void initState() {
    super.initState();
    _loadUserInfo();
  }

  Future<void> _loadUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    final userInfoString = prefs.getString('userInfo');
    if (userInfoString != null) {
      setState(() {
        _userInfo = UserModel.fromJson(jsonDecode(userInfoString));
      });
    }
  }

  Future<void> _logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();
    heartbeatService.stopHeartbeat();

    if (mounted) {
      Navigator.of(context).pushNamedAndRemoveUntil(
        Helper.typeName(LoginScreen), (route) => false,  // 清除所有路由历史
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的信息'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // 头像和基本信息
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  CircleAvatar(
                    radius: 50,
                    backgroundImage: _userInfo?.avatar.isNotEmpty == true
                        ? NetworkImage(_userInfo!.avatar)
                        : null,
                    child: _userInfo?.avatar.isEmpty == true
                        ? const Icon(Icons.person, size: 50)
                        : null,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    _userInfo?.name ?? '未知',
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          // 详细信息
          Card(
            child: Column(
              children: [
                _buildInfoTile('工号', _userInfo?.jobNumber ?? '未知'),
                const Divider(height: 1),
                _buildInfoTile('职位', _userInfo?.department ?? '未知'),
                const Divider(height: 1),
                _buildInfoTile('电话', _userInfo?.mobile ?? '未知'),
              ],
            ),
          ),
          const SizedBox(height: 16),
          // 功能按钮
          Card(
            child: Column(
              children: [
                _buildMenuItem(
                  '修改个人信息',
                  Icons.edit,
                      () async {
                    final result = await Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => EditProfileScreen(userInfo: _userInfo!),
                      ),
                    );
                    if (result == true) {
                      _loadUserInfo();  // 如果更新成功，重新加载用户信息
                    }
                  },
                ),
                const Divider(height: 1),
                _buildMenuItem(
                  '修改密码',
                  Icons.lock,
                      () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ChangePasswordScreen(),
                          ),
                        );
                  },
                ),
                const Divider(height: 1),
                _buildMenuItem(
                  '退出登录',
                  Icons.exit_to_app,
                  _logout,
                  color: Colors.red,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoTile(String label, String value) {
    return ListTile(
      title: Text(
        label,
        style: const TextStyle(
          color: Colors.grey,
          fontSize: 14,
        ),
      ),
      trailing: Text(
        value,
        style: const TextStyle(
          fontSize: 16,
        ),
      ),
    );
  }

  Widget _buildMenuItem(
      String title,
      IconData icon,
      VoidCallback onTap, {
        Color? color,
      }) {
    return ListTile(
      leading: Icon(icon, color: color),
      title: Text(
        title,
        style: TextStyle(color: color),
      ),
      trailing: const Icon(Icons.arrow_forward_ios, size: 16),
      onTap: onTap,
    );
  }
} 